#include "buttongroup.h"

#include <QAbstractButton>

ButtonGroup::ButtonGroup(QObject *parent)
    : QObject(parent)
    , m_buttonGroup(parent)
    , m_pToggledButton(nullptr)
{
    Init();
}

ButtonGroup::~ButtonGroup()
{
    m_buttons.clear();
}

void ButtonGroup::addButton(QAbstractButton *button)
{
    //m_buttonGroup.addButton(button, id);
    if (!m_buttons.contains(button))
    {
        m_buttons.push_back(button);
        connect(button, &QAbstractButton::toggled, this, &ButtonGroup::ButtonToggled);
    }
}

void ButtonGroup::removeButton(QAbstractButton *button)
{
    //m_buttonGroup.removeButton(button);
    m_buttons.removeAll(button);
}

void ButtonGroup::ButtonToggled(bool checked)
{
    QAbstractButton *button = qobject_cast<QAbstractButton*>(sender());
    if (button && checked)
    {
        if (m_pToggledButton)
        {
            m_pToggledButton->toggle();
        }
        m_pToggledButton = button;
    }

    if (!checked && button == m_pToggledButton)
    {
        m_pToggledButton = nullptr;
    }
}

void ButtonGroup::Init()
{
//    connect(&m_buttonGroup, QOverload<QAbstractButton *, bool>::of(&QButtonGroup::buttonToggled),
//            this, QOverload<QAbstractButton *, bool>::of(&ButtonGroup::ButtonToggled));
}
